package com.warm.base.jdk.anno;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

public class CourierNumberValidator implements ConstraintValidator<CourierNumber, Object> {

    // 只允许数字与字母
    private static final Pattern COURIER_NUMBER_REGEX = Pattern.compile("^[0-9a-zA-Z\\-]*$");

    @Override
    public void initialize(CourierNumber constraintAnnotation) {
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 空值由代码中的@NotNull与@NotEmpty去校验
        if (value == null || "".equals(value.toString())
            || !(value instanceof String)) {
            return true;
        }
        return COURIER_NUMBER_REGEX.matcher(value.toString()).matches();
    }
}
